#include<iostream>
#include<string>
#include"Log.hpp"
#include<functional>
#include <cstdint> 
#include <sys/socket.h>
#include<strings.h>
#include<netinet/in.h>
#include<unistd.h>
#include<arpa/inet.h>
#include"InetAddr.hpp"
using namespace std;
using namespace LogModule;

using func_t = function<string (const string& ,InetAddr &)>;

const int default_fd=-1;

class UdpServer
{
public:
    UdpServer(uint16_t port,func_t func)
    {
        _port = port;
        _func = func;
        _sock = default_fd;
        _isrunning = false;
    }
    void Init()
    {
        _sock =socket(AF_INET,SOCK_DGRAM,0);
        if(_sock<0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket create success,sock: " << _sock;
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(_port);
        int n = bind(_sock,(struct sockaddr*)&local,sizeof(local));
        if(n<0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success,port: " << _port;
    }
    void Start()
    {
        _isrunning=true;
        while(_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t s = recvfrom(_sock,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
            cout<<buffer<<endl;
            if(s>0)
            {
                InetAddr client(peer);
                // int peer_port = ntohs(peer.sin_port);
                // string peer_ip = inet_ntoa(peer.sin_addr);
                buffer[s] = 0;
                string result= _func(buffer,client);
                // string result = _func(string(buffer));
                sendto(_sock,result.c_str(),result.size(),0,(struct sockaddr*)&peer,len);
            }
        }
    }
private:
    int _sock;
    uint16_t _port;
    bool _isrunning;
    func_t _func;    
};